// useStockMarketStatus.js
import { ref, onMounted, onUnmounted } from "vue";
export function useStockMarketStatus() {
  const isMarketOpen = ref(false);
  const currentTime = ref("");
  let timer = null;

  const checkMarketStatus = () => {
    const now = new Date();
    const day = now.getDay();
    const hours = now.getHours();
    const minutes = now.getMinutes();
    const currentMinutes = hours * 60 + minutes;

    currentTime.value = now.toLocaleTimeString("zh-CN");

    if (day >= 1 && day <= 5) {
      const isWithinTradingHours =
        currentMinutes >= 9 * 60 + 30 && currentMinutes < 15 * 60;
      isMarketOpen.value = isWithinTradingHours;
      scheduleNextCheck(isWithinTradingHours, currentMinutes);
    } else {
      isMarketOpen.value = false;
      scheduleNextCheck(false, currentMinutes);
    }
  };

  const scheduleNextCheck = (isWithinTradingHours, currentMinutes) => {
    if (timer) {
      clearTimeout(timer);
    }

    let nextCheckDelay;

    if (isWithinTradingHours) {
      // 如果在交易时间内，下次检查安排在收市时（15:00）
      nextCheckDelay = (15 * 60 - currentMinutes) * 60 * 1000;
    } else {
      const nextOpeningMinutes = 9 * 60 + 30; // 9:30
      if (currentMinutes < nextOpeningMinutes) {
        // 如果在今天的开市前，计算到开市的时间
        nextCheckDelay = (nextOpeningMinutes - currentMinutes) * 60 * 1000;
      } else {
        // 如果今天的交易已结束，计算到明天开市的时间
        nextCheckDelay =
          (24 * 60 - currentMinutes + nextOpeningMinutes) * 60 * 1000;
      }
    }

    // 设置下次检查的定时器，但不少于1秒
    timer = setTimeout(checkMarketStatus, Math.max(nextCheckDelay, 1000));
  };

  onMounted(() => {
    checkMarketStatus();
  });

  onUnmounted(() => {
    if (timer) {
      clearTimeout(timer);
    }
  });

  return {
    isMarketOpen,
    currentTime,
  };
}
